package com.tarena.service;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tarena.pojo.Message;
import com.tarena.pojo.MessageType;
import com.tarena.pojo.User;
import com.tarena.utils.ClientMessageQueue;
import com.tarena.utils.ManageUserWindowList;
import com.tarena.view.ChatFriendsWindow;
import com.tarena.view.ChatMainWindow;

import javax.swing.*;
import java.io.*;
import java.lang.reflect.Type;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;

/*线程类*/
public class ClientConnectThread extends Thread{
    private Socket socket;
    private User currentUser;
    private ChatFriendsWindow friendsWindow;
    private ChatMainWindow chatMainWindow;
    private Gson gson = new Gson();
    private OutputStream outputStream;
    private InputStream in;
    private ObjectOutputStream oos;
    private ObjectInputStream ois;
    private ClientMessageQueue queue;

    public ClientConnectThread(Socket socket,User currentUser){
        try {
            this.socket = socket;
            this.currentUser=currentUser;
            outputStream = socket.getOutputStream();
            oos = new ObjectOutputStream(outputStream);
            in = socket.getInputStream();
            ois = new ObjectInputStream(in);
            this.queue = new ClientMessageQueue();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public ClientMessageQueue getQueue() {
        return queue;
    }

    public void setChatMainWindow(ChatMainWindow chatMainWindow) {
        this.chatMainWindow = chatMainWindow;
    }

    /*h获取好友列表*/
    public void getFriends(){
        try {
           /* OutputStream outputStream;=socket.getOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(outputStream);*/
            /*创建mesaages对象*/
            Message message = new Message();
            message.setMagType(MessageType.MESSAGE_GET_ONLINE_FRIENDS);
            oos.writeObject(message);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void initwindow(Message message){
        /*更新界面中的用户列表*/
        String json = message.getContent();
        Type type = new TypeToken<ArrayList<User>>(){}.getType();
        ArrayList<User> users=gson.fromJson(json,type);
        friendsWindow.addDataToJlist(users);
    }

    @Override
    public void run() {
        friendsWindow = new ChatFriendsWindow(socket,currentUser,oos,this);
        friendsWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        friendsWindow.setVisible(true);
        /*获取好友列表*/
        getFriends();
        /*因为线程脱离了main，需要在后台和服务器长连接通信，所以要一直读取信道中的Messgae对象*/
        while (true){
            try {
                /*InputStream in =socket.getInputStream();
                ObjectInputStream ois = new ObjectInputStream(in);*/
                /*如果服务器没有给客户端发送Message对象，线程会一直阻塞（）*/
                Message message =(Message) ois.readObject();
                /*判断message对象的type来决定后续处理方式*/
                if (message.getMagType().equals(MessageType.MESSAGE_RET_ONLINE_FRIENDS)){
                    if(friendsWindow.getSelection()==1){
                        initwindow(message);
                    }
                }
                if(message.getMagType().equals(MessageType.MESSAGE_RET_ALL_FRIENDS)){
                    if(friendsWindow.getSelection()==3){
                        initwindow(message);
                    }
                }
                if(message.getMagType().equals(MessageType.MESSAGE_COMM_MES)){
                    System.out.println(message.getContent());
                    User sender = message.getSender();
                    ChatMainWindow uwf = ManageUserWindowList.findUserWindowFromMap(sender);
                    if(uwf!=null && uwf.isShowing()){
                        uwf.setText(sender.getUsername()+"说:"+message.getContent());
                    }else{
//                        需要写入到消息队列
                        queue.addMsgToQUeue(message.getContent());

                    }

                }

            } catch (IOException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
    }

}
